<template>
  <div>
    <!-- 顶部导航 -->
    <van-nav-bar fixed>
      <template #left>
        <img class="logo" src="../../assets/tou_tiao_logo.png" alt="" />
      </template>
      <template #right>
        <van-icon
        name="search"
        size="0.48rem"
        color="#fff"
        @click="$router.push({ path: '/search' })"/>
      </template>
    </van-nav-bar>
    <!-- 频道导航 -->
    <van-tabs
      v-model="active"
      animated
      sticky
      offset-top="1.226667rem"
      @click="btn"
    >
      <van-tab
        v-for="obj in list"
        :title="obj.name"
        :key="obj.id"
        :name="obj.id"
      >
        <van-pull-refresh
          v-model="isLoading"
          success-text="刷新成功"
          @refresh="onRefresh"
        >
          <van-list
            v-if="articleList.length > 0"
            v-model="loading"
            :finished="finished"
            offset="10"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <ArticcleList :arr="articleList" @action="actionFn"></ArticcleList>
          </van-list>
        </van-pull-refresh>
      </van-tab>
    </van-tabs>
    <!-- 右侧的编辑频道的小图标 -->
    <van-icon
      name="plus"
      size="0.373334rem"
      class="moreChannels"
      @click="show = true"
    />
    <!-- 弹出层组件 -->
    <!-- close-on-click-overlay 是否在点击遮罩层后关闭（false 不关闭） -->
    <van-popup
    v-model="show"
    :close-on-click-overlay="false"
    class="edit_wrap">
      <div class="popup-container">
        <!-- 弹出层的头部区域 -->
        <van-nav-bar title="频道管理">
          <template #right>
            <van-icon
              name="cross"
              size="0.373334rem"
              color="white"
              @click="closePop"
            />
          </template>
        </van-nav-bar>

        <!-- 弹出层的主体区域 -->
        <div class="pop-body">
          <ChannelEdit
          :list="list"
          :unChannelList="unChannelList"
          @del="delFn"
          @add="addFn"
          ref="channel"
          @changeChannel="changeChannelFn"
          ></ChannelEdit>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import {
  channelListAPI,
  allChannelListAPI,
  updateChannelAPI,
  articlesListAPI,
  articleDisLikeAPI,
  articleReportsAPI
} from '@/api'
import ArticcleList from './components/ArticleList'
import ChannelEdit from './components/ChannelEdit'
// 导入 dayjs 的核心模块
import dayjs from 'dayjs'
// 导入计算相对时间的插件
import relativeTime from 'dayjs/plugin/relativeTime' // 到指定时间需要的插件
// 导入本地化的语言包
import zh from 'dayjs/locale/zh-cn'
export default {
  data () {
    return {
      active: 0,
      list: [], // 频道导航列表
      allChannelList: [], // 所有频道数据
      articleList: [], // 文章数据
      isLoading: false, // 下拉状态
      page: 1, // 要的是第几页的数据
      loading: false, // 上拉状态
      finished: false, // 数据是否全部加载完成状态
      channelId: 0, // 要请求的频道id  默认是推荐 0
      show: false // 编辑频道 - 控制弹出层是否展示
    }
  },
  computed: {
    unChannelList () { // 从所有的计算出用户未选的
      return this.allChannelList.filter((item) => {
        const index = this.list.findIndex((obj) => {
          return item.id === obj.id
        })
        if (index === -1) {
          return true
        } else {
          return false
        }
      })
    }
  },
  async created () {
    const [, res] = await channelListAPI()
    this.list = res.data.data.channels
    // 获取所有频道列表
    const [, res1] = await allChannelListAPI()
    this.allChannelList = res1.data.data.channels
    // console.log(this.list)
    this.getArticcleList()
  },
  components: {
    ArticcleList,
    ChannelEdit
  },
  methods: {
    async getArticcleList () {
      // 负责拿文章列表数据
      const [, res] = await articlesListAPI({
        channel_id: this.channelId,
        page: this.page
      })
      res.data.data.results.forEach((obj) => {
        obj.pubdate = this.formatTime(obj.pubdate)
      })
      if (res.data.data.results.length === 0) {
        this.finished = true // 告诉list组件直接底部显示没有更多数据
      } else {
        this.articleList = [...this.articleList, ...res.data.data.results]
        // console.log(res)
        // 等待网络请求结果后, 把下拉刷新状态改为false
        this.isLoading = false // 顶部刷新状态
        this.loading = false // 底部加载更多
      }
    },
    onRefresh () { // 上拉刷新
      this.page = 1
      this.articleList = []
      // 文章下拉事件
      this.getArticcleList()
    },
    onLoad () { // 底部加载更多
      this.page++
      this.getArticcleList()
    },
    btn (channelId) { // 点击切换文章数据
      this.channelId = channelId
      this.page = 1 // 切换频道页码回到1,重新请求数据
      this.articleList = []
      this.getArticcleList()
    },
    formatTime (targetTime) { // 格式化时间
      // 配置语言包
      dayjs.locale(zh)
      // 配置插件
      dayjs.extend(relativeTime)
      const a = dayjs()
      const b = dayjs(targetTime)
      return a.to(b)
    },
    actionResult (err) { // 反馈处理结果
      if (err) {
        // 反馈失败
        console.log('反馈失败')
      } else {
        // 反馈成功
        this.page = 1 // 切换频道页码回到1,重新请求数据
        this.articleList = []
        this.getArticcleList()
      }
    },
    async actionFn (actionObj, artId) { // 反馈事件的方法
      // actionObj: {name: '不感兴趣}...
      if (actionObj.name === '拉黑作者') {
        // 将来调用接口,判断
        return
      }
      if (actionObj.name === '不感兴趣') {
        const [err] = await articleDisLikeAPI({
          target: artId
        })
        this.actionResult(err)
        return
      }
      // 只要不是 拉黑作者 和 不感兴趣 都是二级反馈面板的数据
      const [err] = await articleReportsAPI({
        target: artId,
        type: actionObj.value
      })
      this.actionResult(err)
    },
    async delFn (obj, index) { // 编辑我的频道
      this.list.splice(index, 1)
      const resultList = this.list.filter((obj) => { return obj.id !== 0 }).map((item, index) => {
        const newObj = { ...item }
        newObj.seq = index + 1
        delete newObj.name
        return newObj
      })
      // map 会收集每次遍历 return的值形成一个新的数组
      await updateChannelAPI({
        channels: resultList
      })
    },
    async addFn (obj) { // 新增频道
      this.list.push(obj)
      const resultList = this.list.filter((obj) => { return obj.id !== 0 }).map((item, index) => {
        const newObj = { ...item }
        newObj.seq = index + 1
        delete newObj.name
        return newObj
      })
      await updateChannelAPI({
        channels: resultList
      })
    },
    async closePop () { // 点击弹出层关闭按钮
      this.$refs.channel.isEdit = false // 关闭弹出层里得编辑按钮的状态
      this.show = false// 关闭弹出层
    },
    changeChannelFn (channelId) { // 子组件切换频道方法
      this.show = false
      this.active = channelId

      this.channelId = channelId
      this.page = 1
      this.articleList = []
      this.getArticcleList()
    }
  }
}
</script>

<style scoped lang="less">
/deep/ .van-tabs__content {
  padding-top: 44px;
}
.logo {
  height: 80%;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 62px;
  right: 8px;
  z-index: 999;
}

// 弹出层容器宽度高度铺满屏幕
/*频道编辑弹出层 */
.edit_wrap {
  width: 100%;
  height: 100%;
}
</style>
